<?php
namespace app\wechat\controller;

use thirdapi\tp_wechat\Wechat;
use think\Cache;
use think\Session;

/**
 * 前台通用控制器
 * 主要获取首页聚合数据
 */
class AuthController extends CommonController {
    protected $isWechatBrowser = false;
    protected $scope = 'snsapi_base';
    protected $uuid;
    protected $open_id;
    protected $member_info;
    protected $user_info;
    protected $options;
    protected $isReg = false;
    protected $no_login = false;
    protected $system_config = [];
    protected $last_update_time;
    protected $jsSign =[
        'appId' => '',
        'timestamp' => '',
        'nonceStr' => '',
        'signature' => '',
        'url' => ''
    ];
    protected $order_status;
    protected $shipping_status;
    protected $pay_status;
    protected $pay_code;
    protected $navUrlArr = [
        'paysuccess'
    ];
    public function _initialize()
    {
        $this->order_status = config('ORDER_STATUS');
        $this->shipping_status = config('SHIPPING_STATUS');
        $this->pay_status = config('PAY_STATUS');
        $this->pay_code = config('PAY_CODE');
        parent::_initialize(); // TODO: Change the autogenerated stub
        $system_config = db('System')->where(['id'=>['>','0']])->find();
        $user_agent = $this->request->server('HTTP_USER_AGENT');
        if (!$this->options) $this->getOptions();
        if (!strpos($user_agent, 'MicroMessenger') === false ) $this->isWechatBrowser = true;
        //判断提交方式和是否微信浏览器
        if ($this->request->method() == 'GET' && $this->isWechatBrowser === true){
            //未登录 重新登录
            if (!$this->checkAuth()&& !$this->no_login)  $this->wxoauth();
            $this->isLogin = true;
            //设置全局登录
            $this->loginGlobal();
            if($this->isReg){
             //   if(!$this->checkUuidMobile()) $this->redirect('/index/WC_html_1/mainContainer.html#user/user_blind.html');
            }
            $script = Wechat::script($this->options);
            $this->jsSign = $script->getJsSign('http://'.$this->options['web_url'].$this->request->url());
            $this->jsSign['url'] = 'http://'.$this->options['web_url'].$this->request->url();
        }
        if($system_config){
            $system_config['logo'] = 'http://'.$this->options['web_url'].'/public'.$system_config['logo'];    
        }
        
        if($this->user_info && (empty($this->user_info['id']))||$this->user_info['id']<=0){
            $user_info = model('User')->where(['openid'=>$this->open_id])->find();
            if($user_info){
                $this->user_info = $user_info;
                Session::set('user_info',$user_info,'html5');
            }
        }
        $openid = '';
        if(Session::has('user_info','html5')){
            $openid = Session::get('user_info','html5')['openid'];
        }
        $currentUrl = url();
        $currentUrlArr = explode('/',$currentUrl);
        $isCheck = true;
        if(count($currentUrlArr)>0){
            $urlLastInd = count($currentUrlArr)-1;
            $actionArr = explode('.',$currentUrlArr[$urlLastInd]);
            if(in_array($actionArr[0],$this->navUrlArr)){
                $isCheck = false;
            }
        }
        if($isCheck){
            if(!isset($this->user_info['store_id']) || empty($this->user_info['store_id']) || $this->user_info['store_id']<=0){
                $user_info = model('User')->where(['openid'=>$openid])->find();
                if($user_info && $user_info['store_id']>0){
                    $this->user_info['store_id'] = $user_info['store_id'];
                }else{
                    $this->error('请联系门店管理员');
                    exit;
                }
            }
        }
        checkOrders();

        $this->assign([
            'sys_config'=>$system_config,
            'wx_config'=>$this->jsSign,
            'member_info'=>$this->member_info,
            'order_status' => $this->order_status,
            'shipping_status' => $this->shipping_status,
            'pay_status' => $this->pay_status,
            'pay_code' => $this->pay_code
        ]);
    }

    /**
     * 设置全局登录
     * #User: thirdapi
     * #Email:776329498@qq.com
     * #Date:
     * @return bool
     */
    public function loginGlobal(){
        if (!$this->open_id) return false;
        $member = model('User');
        $member_info = $member->where(['openid'=>$this->open_id])->find();
        $wxAccount = db('WxAccount')->where(['appid'=>$this->options["appid"]])->find();
        $data = [
            'nickname' => $this->member_info['nickname'],
            'headimgurl' => $this->member_info['headimgurl'],
            'openid' => $this->open_id,
            'distributor_id' => 0,
            'total_commission' => 0,
            'money' => 0,
            'integral' => 0,
            'consumption_price' => 0,
            'consumption_integral' => 0,
            'sm_time' => time(),
            'sex' => $this->member_info['sex'],
            'vip' => 0,
            'uuid' => '',
            'account_id' => $wxAccount['id']
        ];
        if (!$member_info){
            $member -> save($data);
            $member_info = $member->where(['openid'=>$this->open_id])->find();
            $this->isReg = true;
        }
        $fans = model('WxFans');
        $fans_info = $fans->where(['openid'=>$this->open_id])->find();
        //$this->member_info['appid'] = $this->getOptions();
        if (!$fans_info){
            $fans->save($data);
        }else{
            $fans->where(['id' => $fans_info['id']])->update($data);
        }
        //设置全局登录 微信浏览器登录
        if (!$this->checkLoginGlobal())  $this->setLoginGlobal($member_info,2);
        $this->uuid = $member_info['uuid'];
    }

    /**
     * 微信内页登录
     * #User: Mikkle
     * #Email:776329498@qq.com
     * #Date:
     * @return bool
     */
    public function wxoauth()
    {
        if ($this->checkAuth()) return false;
        $code = $this->request->param('code');
        if (Session::has('code','html5') && $code == Session::get('code','html5') && $code) return false;
        if (!$this->options) $this->getOptions();
        $options = [
            'token'=>$this->options["token"], //填写你设定的key
            'appid'=>$this->options["appid"], //填写高级调用功能的app id
            'appsecret'=>$this->options["appsecret"] //填写高级调用功能的密钥
        ];
        Session::set('appid',$this->options["appid"],'html5');
        $we_obj = Wechat::oauth($this->options);
        if ($code) {
            $json = $we_obj->getOauthAccessToken();
            if (!$json) {
                $this->redirect($this->request->baseUrl());
               // die('获取用户授权失败，请重新确认<a href="'.$this->request->baseUrl().'" >点击重试</a>');
            }
            $this->open_id = $json["openid"];
            $access_token = $json['access_token'];
            Session::set('open_id',$this->open_id,'html5');
            Session::set('code',$code,'html5');
            $user_info = $we_obj->getUserInfo($this->open_id);
            $user_info['appid']=Session::get('appid','html5');
            if ($user_info && !empty($user_info['nickname'])) {
                $this->member_info = $user_info;
            } elseif (strstr($json['scope'],'snsapi_userinfo')!==false) {
                $user_info = $we_obj->getOauthUserinfo($access_token,$this->open_id);
                $user_info['appid'] = Session::get('appid','html5');
                if ($user_info && !empty($user_info['nickname'])) {
                    $this->member_info = $user_info;
                } else {
                    return $this->open_id;
                }
            }
            if ($this->member_info) {
                Session::set('member_info',$this->member_info,'html5');
                Session::set('open_id',$this->open_id,'html5');
                Session::delete('wx_redirect','html5');
                return $this->open_id;
            }
            $this->scope = 'snsapi_userinfo';
        }

        if ($this->scope=='snsapi_base') {
            $url = $this->request->url(true);
            Session::set('wx_redirect',$url,'html5');
        } else {
            $url =Session::get('wx_redirect','html5');
        }
        if (!$url) {
            Session::delete('wx_redirect','html5');
            die('获取用户授权失败');
        }

        $oauth_url = $we_obj->getOauthRedirect($url,"wxbase",$this->scope);
        header('Location:'.$oauth_url);
        die;
    }

    /**
     * 获取微信Options 使用缓存
     * #User: Mikkle
     * #Email:776329498@qq.com
     * #Date:
     * @param int $appid
     * @return mixed
     */
    public function getOptions($appid = 'wx2c23698c4f2d86ee'){
        if(Cache::has('weOptions')){
            $weOptions = Cache::get('weOptions');
        }else{
            $weOptions = model('WxAccount')->where(['appid' => $appid])->find();
            Cache::set('weOptions',$weOptions,3600);
        }
        $this->options = $weOptions;
        $this->appid = $weOptions["appid"];
        return $weOptions["appid"];

    }

    /**
     * 判断登录是否成功
     * #User: Mikkle
     * #Email:776329498@qq.com
     * #Date:
     * @return bool
     */
    public function checkAuth()
    {
        if (!Session::has('member_info','html5')&&!Session::has('open_id','html5')){
            return false;
        }else{
            $this->member_info = Session::get('member_info','html5');
            $this->open_id = Session::get('open_id','html5');
            $this->appid = Session::get('appid','html5');
            if(!Session::has('member_info','html5')&&Session::has('open_id','html5')){
                $user_info = model('User')->where(['openid'=>$this->open_id])->find();
                if(!$user_info){
                    $this->member_info['id'] = $user_info['id'];
                   return false; 
                }
                Session::set('member_info',$this->member_info,'html5');
            }
            
            if(!Session::has('user_info','html5')&&!empty($this->open_id)){
                $user_info = model('User')->where(['openid'=>$this->open_id])->find();
                if($user_info){
                    $this->user_info = $user_info;
                    Session::set('user_info',$user_info,'html5');
                }
            }
            if (!$this->options) $this->getOptions();
            return true;
        }
    }
}